package Diagnosis

import (
	"MedicalTreatment/global"
	model "MedicalTreatment/model"
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type DrugRes struct {
	DocketId           int    `gorm:"type:int(100)"`
	PatientId          int    `gorm:"type:int(100)"`
	Department         string `gorm:"type:varchar(100)"`
	SymptomDescription string `gorm:"type:varchar(100)"`
	Diagnosis          string `gorm:"type:varchar(100)"`
	IsHospital         string `gorm:"type:boolean"`
	HospitalStay       string `gorm:"type:varchar(100)"`
	DrugId             []uint `gorm:"type:bigint(20)"`
	Number             []int  `gorm:"type:int(100)"`
	Data               string `gorm:"type:varchar(100)"`
}

func DiaAdd(r *gin.Engine) {
	r.POST("/diaAdd", func(context *gin.Context) {
		var drugRes DrugRes
		if err := context.ShouldBindJSON(&drugRes); err != nil {
			context.JSON(200, gin.H{
				"Msg": err,
			})
			return
		}
		var reg model.Register
		number := global.DB.Model(model.Register{}).Where("doc_id = ? AND pat_id = ? AND date LIKE ?", drugRes.DocketId, drugRes.PatientId, drugRes.Data+"%").Find(&reg).RowsAffected
		fmt.Println(number)
		if number != 0 {
			var pat model.Patient
			if err := global.DB.Model(model.Patient{}).Where("id = ?", drugRes.PatientId).First(&pat).Error; err != nil {
				context.JSON(200, gin.H{
					"Msg": err,
				})
				return
			}
			var doc model.Docket
			if err := global.DB.Model(model.Docket{}).Where("id = ?", drugRes.DocketId).First(&doc).Error; err != nil {
				context.JSON(200, gin.H{
					"Msg": err,
				})
				return
			}
			res := model.Result{
				Model:              gorm.Model{},
				DocketId:           drugRes.DocketId,
				DoctorName:         doc.Name,
				PatientId:          drugRes.PatientId,
				PatientName:        pat.Patient_name,
				Department:         doc.Docket_department,
				PatientSex:         pat.Patient_sex,
				PatientIDcard:      pat.Patient_idCard,
				PatientAge:         pat.Patient_age,
				SymptomDescription: drugRes.SymptomDescription,
				Diagnosis:          drugRes.Diagnosis,
				IsHospital:         drugRes.IsHospital,
				HospitalStay:       drugRes.HospitalStay,
			}

			if err := global.DB.Model(model.Result{}).Create(&res).Error; err != nil {
				context.JSON(200, gin.H{
					"Msg": err,
				})
				return
			} else {
				for i := 0; i < len(drugRes.DrugId); i++ {
					drug := model.DrugList{
						Model:    gorm.Model{},
						DrugId:   drugRes.DrugId[i],
						ResultId: res.ID,
						Number:   drugRes.Number[i],
					}

					if err := global.DB.Model(model.DrugList{}).Create(&drug).Error; err != nil {
						context.JSON(200, gin.H{
							"Msg": err,
						})
						return
					}
				}
				context.JSON(200, gin.H{
					"Msg": "创建成功",
				})
			}

		} else {
			context.JSON(200, gin.H{
				"Msg": "该患者和医生不存在绑定关系",
			})
		}
	})
}
